#include "ImageIO.h"

IplImage* readImage( char* FileName )
{
	IplImage* newImage = new IplImage();
	if ( (newImage = cvLoadImage( FileName, 1)) == 0)
	{
		cout<<"Fail to read image."<<endl;
		exit(0);
	}
	cout<<"Successfully load image..."<<endl;
	return newImage;
}

void readInputParameters(int argc, char** argv){
	if ( argc >= 2){
		rawImage = readImage( argv[1] );
		if (argc >= 3){
			THRESHOLD = atoi(argv[2]);
			if (argc >=4){
				AREA_RATIO = atof(argv[3]);
				if( argc >=5 ){
					MODEL_HEIGHT = atoi(argv[4]);
					MODEL_WIDTH = MODEL_HEIGHT;
					if (argc >= 6) {
						MERGE_HEIGHT = atoi(argv[5]);
						MERGE_WIDTH = MERGE_HEIGHT;
						if (argc >= 8){
							CENTERX = atoi(argv[6]);
							CENTERY = atoi(argv[7]);
						}
					}
				}
			}
		}
	} else{
		rawImage = readImage("../90.jpeg");
		//CENTERX = rawImage->width/2;
		//CENTERY = rawImage->height/2;
	}
}


void cleanUp()
{
	delete [] edgeHash;
	delete [] tipHash;
	cvReleaseImage(&rawImage);
	cvReleaseImage(&binaryImage);
	cvReleaseImage(&skinImage);
	cvReleaseImage(&structureImage);
	cvDestroyAllWindows();
}

void saveRawStructureImage(){
	IplImage* newImage = cvCreateImage(cvGetSize(rawImage),rawImage->depth,3);
	uchar* newPtr = (uchar*)newImage->imageData;
	uchar* rawPtr = (uchar*)rawImage->imageData;
	uchar* strPtr = (uchar*)structureImage->imageData;
	memcpy(newPtr, rawPtr, sizeof(uchar)*newImage->height*newImage->widthStep);
	for (int i = 0; i < newImage->height; i++){
		for (int j = 0; j < newImage->width; j++){
			if (strPtr[i*newImage->widthStep+j*3+2] == 255 &&
				strPtr[i*newImage->widthStep+j*3+1] == 0){
					newPtr[i*newImage->widthStep+j*3+0] = 225;
					newPtr[i*newImage->widthStep+j*3+1] = 225;
					newPtr[i*newImage->widthStep+j*3+2] = 225;
			}
			if (strPtr[i*newImage->widthStep+j*3] == 255 &&
				strPtr[i*newImage->widthStep+j*3+2] == 0){
					newPtr[i*newImage->widthStep+j*3+0] = 225;
					newPtr[i*newImage->widthStep+j*3+1] = 200;
					newPtr[i*newImage->widthStep+j*3+2] = 200;
			}
		}
	}
	cvSaveImage("../RawStructure.bmp",newImage);
	cvReleaseImage(&newImage);
}